/**
 * Theme: Minton Admin Template
 * Author: Coderthemes
 * Component: Editable
 * <p>
 *     1、实现可编辑表格；
 *     2、实现产品添加；
 *     3，实现产品修改；
 *     4，实现产品删除
 * </p>
 *
 */


var tables;
(function( $ ) {

	'use strict';

	var EditableTable = {

		options: {
			addButton: '#addToTable',
			table: '#datatable-editable',
			dialog: {
				wrapper: '#dialog',
				cancelButton: '#dialogCancel',
				confirmButton: '#dialogConfirm',
			}
		},

		initialize: function() {
			this
				.setVars()
				.build()
				.events();
		},

		setVars: function() {
			this.$table				= $( this.options.table );
			this.$addButton			= $( this.options.addButton );

			// dialog
			this.dialog				= {};
			this.dialog.$wrapper	= $( this.options.dialog.wrapper );
			this.dialog.$cancel		= $( this.options.dialog.cancelButton );
			this.dialog.$confirm	= $( this.options.dialog.confirmButton );

			return this;
		},

		build: function() {
			tables=this.datatable = this.$table.DataTable({
				"iDisplayLength": 50,
				"sDom": "t<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
				"language": {
					"decimal":        "",
					"emptyTable":     "没有数据",
					"info":           "从 _START_ 条到 _END_ 条共 _TOTAL_ 条",
					"infoEmpty":      "从 0 到 0 页共 0 页",
					"infoFiltered":   "(总共 _MAX_ 条)",
					"infoPostFix":    "",
					"thousands":      ",",
					"lengthMenu":     "显示 _MENU_ 页",
					"loadingRecords": "Loading...",
					"processing":     "Processing...",
					"search":         "搜索:",
					"zeroRecords":    "No matching records found",
					"paginate": {
						"first":      "第一页",
						"last":       "最后一页",
						"next":       "下一页",
						"previous":   "上一页"
					},
				},
				"ordering": false,
				aoColumns: [
					null,
					null,
					null,
					null,
					null,
					null,
					{ "bSortable": false }
				]
			});

			window.dt = this.datatable;

			return this;
		},


		events: function() {
			var _self = this;

			this.$table
				.on('click', 'a.save-row', function( e ) {
					e.preventDefault();
					_self.rowSave( $(this).closest( 'tr' ) );
				})
				.on('click', 'a.cancel-row', function( e ) {
					e.preventDefault();

					_self.rowCancel( $(this).closest( 'tr' ) );
				})
				.on('click', 'a.edit-row', function( e ) {
					e.preventDefault();
					_self.rowEdit( $(this).closest( 'tr' ) ,"");
				})
				.on( 'click', 'a.remove-row', function( e ) {
					e.preventDefault();

					var $row = $(this).closest( 'tr' );

					_self.rowRemove( $row );
				});

			this.$addButton.on( 'click', function(e) {
				e.preventDefault();

				_self.rowAdd();
			});

			this.dialog.$cancel.on( 'click', function( e ) {
				e.preventDefault();
				$.magnificPopup.close();
			});

			return this;
		},

		// ==========================================================================================
		// ROW FUNCTIONS
		// ==========================================================================================
		rowAdd: function() {
			this.$addButton.attr({ 'disabled': 'disabled' });

			var actions,
				data,
				$row,
				selects;

			actions = [
				'<a href="#" class="hidden on-editing save-row m-r-10"><i class="fa fa-save fa-18"></i></a>',
				'<a href="#" class="hidden on-editing cancel-row m-r-10"><i class="fa fa-times fa-18"></i></a>',
				'<a href="#" class="on-default edit-row m-r-10"><i class="fa fa-pencil fa-18"></i></a>',
				'<a href="#" class="on-default remove-row m-r-10"><i class="fa fa-trash-o fa-18"></i></a>'
			].join(' ');

			selects = ['<select style="width:120px; height:32px;"><option value="1">普通包</option>' +
			'<option value="2">其他包</option></select>'].join(' ');

			data = this.datatable.row.add([ '',selects, '','','','', actions ]);
			$row = this.datatable.row( data[0] ).nodes().to$();
			$row.find( 'td' ).eq(4).addClass( 'hidden' );
			$row
				.addClass( 'adding' )
				.find( 'td:last' )
				.addClass( 'actions' );

			this.rowEdit( $row ,"aa");

			this.datatable.order([0,'asc']).draw(); // always show fields
		},

		rowCancel: function( $row ) {
			var _self = this,
				$actions,
				i,
				data;

			if ( $row.hasClass('adding') ) {
				this.rowRemove( $row );
			} else {

				data = this.datatable.row( $row.get(0) ).data();
				this.datatable.row( $row.get(0) ).data( data );

				$actions = $row.find('td.actions');
				if ( $actions.get(0) ) {
					this.rowSetActionsDefault( $row );
				}

				this.datatable.draw();
			}
		},

		rowEdit: function( $row,aa ) {
			var _self = this,
				data;

			data = this.datatable.row( $row.get(0) ).data();

			$row.children( 'td' ).each(function( i ) {
				var $this = $( this );
				if ( $this.hasClass('actions') ) {
					_self.rowSetActionsEditing( $row );
				} else {
					if(i == 1){
						var selected = $row.find("select").val();//下拉默认选中赋值
						_self.rowSetActionsEditing( $row );
						$row.find("select").val(selected);
					}else if(i==4){
						//生成产品编码
						if(!aa){
							$this.html( '<input type="text" class="form-control input-block" value="' + data[i] + '"/>' );
						}else {
							var mth = (Math.random()*1000000000000+"").substr(0,11);
							$this.html( '<input type="hidden" class="form-control input-block" value="' + mth + '"/>' );
						}
					}else {
						$this.html( '<input type="text" class="form-control input-block" value="' + data[i] + '"/>' );
					}
				}
			});
		},

		rowSave: function( $row ) {
			var _self     = this,
				$actions,
				$selectVal,
				values    = [];

			if ( $row.hasClass( 'adding' ) ) {
				this.$addButton.removeAttr( 'disabled' );
				$row.removeClass( 'adding' );
			}

			values = $row.find('td').map(function() {
				var $this = $(this);

				if ( $this.hasClass('actions') ) {
					_self.rowSetActionsDefault( $row );
					return _self.datatable.cell( this ).data();
				} else {
					if($this.index() == 1){
						$selectVal = $this.find("select").val();
						_self.rowSetActionsDefault( $row );
						return _self.datatable.cell( this ).data();
					}else {
						return $.trim( $this.find('input').val() );
					}
				}
			});

			/**
			 * 验证信息是否为空
			 */
			if(!values[0]){
				checkOut($row,"产品名称不能为空");
				return false;
			}else if(!values[2]){
				checkOut($row,"产品价格不能为空");
				return false;
			}else if(isNaN(values[2])){
				checkOut($row,"产品价格格式错误");
				return false;
			}else if(!$selectVal){
				checkOut($row,"流量类型不能为空");
				return false;
			}else if(!values[5]){
				checkOut($row,"产品包体不能为空");
				return false;
			}
			/*
			 * 参数提交前校验
			 */
			function checkOut($row,msg) {
				messageWarn(msg);
				$row.find('a:eq(0)').removeClass("hidden");
				$row.find('a:eq(1)').removeClass("hidden");
				$row.find('a:eq(2)').addClass("hidden");
				$row.find('a:eq(3)').addClass("hidden");
			}
			this.datatable.row( $row.get(0) ).data( values );
			$row.find("select").val($selectVal);
			//新增或修改
			console.log("values:"+values[0]+","+values[1]+","+values[2]+","+values[4]);
			var id = $("#id").val();
			var param={"productName":values[0],"groupId":id,"remark":values[3],"ptype":$selectVal,"price":values[2],"productKey":values[4],"packages":values[5]};
			H5Requset("admin/mProduct/insertMProduct",param,"");
			$actions = $row.find('td.actions');
			if ( $actions.get(0) ) {
				this.rowSetActionsDefault( $row );
			}
			this.datatable.draw();
		},

		rowRemove: function( $row ) {
			if ( $row.hasClass('adding') ) {
				this.$addButton.removeAttr( 'disabled' );
			}
			//start 删除 获取产品编码，根据产品编码删除产品
			var id = $row.find("td").eq(4).text();
			if(!id){
				tables.row( $row.get(0) ).remove().draw();
				return false;
			}
			swal({
				title: "系统提示",
				text: "确定要删除该产品吗?",
				type: "warning",
				showCancelButton: true,
				confirmButtonColor: "#FF8247",
				confirmButtonText: "确定删除",
				cancelButtonText: "取消操作",
				closeOnConfirm: false,
				closeOnCancel: true
			}, function (isConfirm) {
				if(isConfirm){
					H5DelData("get","admin/mProduct/deleteMProduct",{"id":id},"");
					tables.row( $row.get(0) ).remove().draw();
				}
			});
			//end 删除
		},
		rowSetActionsEditing: function( $row ) {
			$row.find( '.on-editing' ).removeClass( 'hidden' );
			$row.find( '.on-default' ).addClass( 'hidden' );
		},
		rowSetActionsDefault: function( $row ) {
			$row.find( '.on-editing' ).addClass( 'hidden' );
			$row.find( '.on-default' ).removeClass( 'hidden' );
		}
	};

	$(function() {
		EditableTable.initialize();
	});

}).apply( this, [ jQuery ]);